package com.hylanda.processor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.nifi.annotation.behavior.ReadsAttribute;
import org.apache.nifi.annotation.behavior.ReadsAttributes;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.util.StringUtils;

/**
 * 
 * @author linda
 * @version created at：2017年12月27日
 * 
 */
@Tags({ "valley", "bullseye" })
@CapabilityDescription("接收上层传递的数据，写入Azure上的platform数据库的" + BullseyeProcessor.DATA_TABLE + "；在配置界面中配置展现参数，写入"
		+ BullseyeProcessor.CFG_TABLE + "表；" + "通过平台提供的接口获取processor_id，并写入两张相关表。")
@SeeAlso({})
@ReadsAttributes({ @ReadsAttribute(attribute = "", description = "") })
@WritesAttributes({ @WritesAttribute(attribute = "", description = "") })
public class BullseyeProcessor extends ReportProcessor {
	static final String CFG_TABLE = "[M_Bull's-eye_cfg]";
	static final String DATA_TABLE = "[M_Bull's-eye]";
	static final int COLUMN_SIZE = 5;

	// 模型显示配置
	public static final PropertyDescriptor TITLE_PROPERTY = new PropertyDescriptor.Builder().name("title")
			.displayName("◆            标题").description("靶心图模型中需要显示的标题").required(false)
			.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).defaultValue("重点xx分布分析").build();
	// 模型数据配置
	public static final PropertyDescriptor OBJECT_PROPERTY = new PropertyDescriptor.Builder()
			.name(COLUMN_PREFIX + "0").displayName("◆            对象").description("待分析对象字段名称").required(false)
			.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();

	public static final PropertyDescriptor VALUES_PROPERTY = new PropertyDescriptor.Builder()
			.name(COLUMN_PREFIX + "1").displayName("◆            大小").description("大小字段名称，类型为bigint")
			.required(false).addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();

	public static final PropertyDescriptor RADIUS_PROPERTY = new PropertyDescriptor.Builder()
			.name(COLUMN_PREFIX + "2").displayName("◆            与靶心距离").description("与靶心距离字段名称，类型为bigint").required(false)
			.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();

	public static final PropertyDescriptor COLOR_PROPERTY = new PropertyDescriptor.Builder()
			.name(COLUMN_PREFIX + "3").displayName("◆            对象颜色")
			.description("对象颜色字段名称，格式：rgba(250,200,100,0.8)").required(false)
			.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();

	public static final PropertyDescriptor URL_PROPERTY = new PropertyDescriptor.Builder()
			.name(COLUMN_PREFIX + "4").displayName("◆            链接").description("链接字段名称").required(false)
			.addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build();

	public BullseyeProcessor() {
		super(DATA_TABLE, CFG_TABLE, COLUMN_SIZE);
	}

	@Override
	protected void init(final ProcessorInitializationContext context) {
		super.init(context);
		final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
		descriptors.add(CFG_DESCRIPTOR);
		descriptors.add(TITLE_PROPERTY);

		descriptors.add(DATA_DESCRIPTOR);
		descriptors.add(OBJECT_PROPERTY);
		descriptors.add(VALUES_PROPERTY);
		descriptors.add(RADIUS_PROPERTY);
		descriptors.add(COLOR_PROPERTY);
		descriptors.add(URL_PROPERTY);

		descriptors.add(CONTROL_DESCRIPTOR);
		descriptors.add(CONTROL_VALUES);

		this.descriptors = Collections.unmodifiableList(descriptors);
	}

	@Override
	protected void saveCfg(ProcessContext context, String[] columns) throws Exception {
		final ComponentLog logger = getLogger();
		// 添加配置信息
		final String title = context.getProperty(TITLE_PROPERTY).getValue();
		final StringBuilder sqlAccumulator1 = new StringBuilder();
		sqlAccumulator1.append("if not exists (select 1 from ").append(CFG_TABLE)
				.append(" where processor_id = '").append(getIdentifier()).append("' )");
		sqlAccumulator1.append("insert into ").append(CFG_TABLE).append("(processor_id, title) values('")
				.append(getIdentifier()).append("', '").append(title).append("') ");
		sqlAccumulator1.append("else update ").append(CFG_TABLE).append(" set title = '").append(title)
				.append("' where processor_id = '").append(getIdentifier()).append("'");
		logger.debug(sqlAccumulator1.toString());
		final StringBuilder sqlAccumulator = new StringBuilder();
		// 添加数据信息
		if (!StringUtils.isEmpty(columns[0])) {
			try {
				final Long valuesL = Long.parseLong(columns[1]);
				final Long radiusL = Long.parseLong(columns[2]);
				sqlAccumulator.append("insert into ").append(DATA_TABLE)
						.append("(processor_id,name,radius,color,url,").append(VALUES);
				sqlAccumulator.append(") values('").append(getIdentifier()).append("','").append(columns[0])
						.append("',").append(radiusL).append(",'").append(columns[3]).append("','")
						.append(columns[4]).append("',").append(valuesL);
				sqlAccumulator.append(")");
			} catch (Exception e) {
				sqlAccumulator.setLength(0);
				logger.error("saveDataToDB {} error {}", new Object[] { DATA_TABLE, e.getMessage() });
			}
			logger.debug(sqlAccumulator.toString());
		}
		this.saveToDB(sqlAccumulator1, sqlAccumulator);
	}
}
